# coding:utf-8
from sqlalchemy import Column, String, Integer, DateTime, or_

from database import dbconnect, session_maker, model_list

_, _, DBase = dbconnect()


class CloudResource(DBase):
    __tablename__ = 'cmdb_cloud_resource'
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True)
    org = Column(String(255))   # 组织
    project = Column(String(255))   # 项目
    res_type = Column(String(255))   # 资源类型
    instance_id = Column(String(255))   # 实例ID or bucket
    ip_private = Column(String(255))       # 内网IP
    ip_public = Column(String(255))        # 公网IP
    cpu = Column(String(255))   # CPU核心数
    mem = Column(String(255))  # 内存容量（GB）
    sys_disk = Column(String(255))  # 系统盘大小（GB）
    data_disk = Column(String(255))  # 数据盘大小（GB）
    system_version = Column(String(255))   # 系统版本
    res_function = Column(String(255))     # 资源功能
    comment = Column(String(255))  # 备注
    cpu_use_percent = Column(String(255))  # cpu使用率
    mem_use_percent = Column(String(255))  # mem使用率
    disk_use_percent = Column(String(255))  # 磁盘使用率
    oss_use = Column(String(255))
    expire_time = Column(String(255))
    create_time = Column(DateTime)
    update_time = Column(DateTime)

    # 废纸篓操作
    is_deleted = Column(Integer)
    delete_time = Column(DateTime)


    # 查询所有
    def find_all(self):
        with session_maker() as session:
            result = session.query(CloudResource).filter(
                or_(
                    CloudResource.is_deleted != 1,
                    CloudResource.is_deleted == None
                )
            ).all()
            return model_list(result)

    # 根据id查询
    def find_deleted(self):
        with session_maker() as session:
            result = session.query(CloudResource).filter(CloudResource.is_deleted == 1).all()
            return model_list(result)

    # 执行原生sql
    def exec_sql(self, raw_sql):
        with session_maker() as session:
            res = session.execute(raw_sql)  # res是获取的对象
            # all_res_list = res.fetchall()  # all_res_list具体的结果 是列表
            print(res.rowcount)
            return res.rowcount


if __name__ == '__main__':
    a = CloudResource()
    li = a.find_all()
    print(li)
